package com.web;

import com.javabean.Book;
import com.javabean.Cart;
import com.javabean.CartItem;
import com.javabean.User;
import com.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CartServlet extends BaseServlet {
    BookServiceImpl a = new BookServiceImpl();

    public void addItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取id参数
        String id = request.getParameter("id");
        int i = Integer.parseInt(id);
        //根据id查询图书的信息
        Book book = a.queryBookById(i);
        CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice(), book.getPrice());
        request.getSession().setAttribute("lastName", cartItem.getName());
        //获取session域中的购物车对象
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            request.getSession().setAttribute("cart", cart);
        }

        if (book.getStock() > 0) {
            cart.addItem(cartItem);
        }
        //重定向会原来商品所在的地址页面
        response.sendRedirect(request.getHeader("Referer"));
    }

    public void deleteItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得要删除商品的id
        String id = request.getParameter("id");
        int i = Integer.parseInt(id);
        //获取session域中的购物车对象
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart != null) {
            cart.deleteItem(i);
        }
        response.sendRedirect(request.getHeader("Referer"));
    }

    public void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取session域中的购物车对象
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart != null) {
            cart.clear();
            response.sendRedirect(request.getHeader("Referer"));
        }
    }

    public void updateCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得要修改商品的id与count
        String id = request.getParameter("id");
        String count = request.getParameter("count");
        int i = Integer.parseInt(id);
        int j = Integer.parseInt(count);
        //获取session域中的购物车对象
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart != null) {
            cart.updateCount(i, j);
            response.sendRedirect(request.getHeader("Referer"));
        }
    }


}
